package com.hussein.android.quizgame.controllers;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.content.SharedPreferences;
import android.database.SQLException;
import android.util.Log;

import com.hussein.android.quizgame.QuestionActivity;
import com.hussein.android.quizgame.model.Question;
import com.hussein.android.quizgame.utils.DataBaseHelper;
import com.hussein.android.quizgame.utils.Globals;

public class QuestionController {
	private QuestionActivity caller;

	public QuestionController(QuestionActivity caller) {
		this.caller = caller;
	}

	public void setScore(int score) {
		this.score = score;
	}

	public void setQ(int qNum) {
		this.qNum = qNum;
	}

	public void setNumberOfQuestuons(int numOfQuestions) {
		this.numOfQuestions = numOfQuestions;
	}

	private List<Question> list = new ArrayList<Question>();
	int qNum = 0;
	int score = 0;
	private int numOfQuestions = 10;
	private int category = 2;

	public void init(SharedPreferences prefs) {
		init();
	}

	public void init() {

		DataBaseHelper myDbHelper = new DataBaseHelper((Context) caller);

		try {

			myDbHelper.createDataBase();

		} catch (IOException ioe) {

			throw new Error("Unable to create database");

		}

		try {

			myDbHelper.openDataBase();

		} catch (SQLException sqle) {

			throw sqle;

		}

		list = myDbHelper.getQuestionSet(category, numOfQuestions);

		myDbHelper.close();

	}

	public Question getNextQuestion() {

		if (qNum < list.size())
			return list.get(qNum++);
		else {
			// saveScore();
			return null;
		}

	}

	public boolean submitAnswerAndEvaluate(int i, int time) {

		if (list.get(qNum - 1).getRightAnswer() != (i + 1))
			return false;

		score = score + (time * 100);
		return true;

	}

	public String getCorrectAnswer() {

		String answer = "";
		try {
			int ans = list.get(qNum - 1).getRightAnswer();
			answer = (list.get(qNum - 1).getAnswers())[ans - 1];
		} catch (Exception e) {
			Log.d("QUIZTRIVIAL", e.getMessage());
		}

		return answer;
	}

	public int getScore() {
		return score;
	}

	public int getQuestionNumber() {
		return qNum;
	}

	public int getNumberOfQuestions() {
		return numOfQuestions;
	}

}
